<template>
  <div class="login-page">
    <div class="top flex_ai_c flex_js_c">
      <img class="login-bg" src="../../assets/img/login_bg.jpg" />
      <div class="login-card flex_ai_c flex_js_c">
        <!-- 账号密码登录 -->
        <div class="main-card" v-if="loginPhone==0">
          <div class="title flex_ai_c flex_jc_sb">
            <span>欢迎登录</span>
            <span @click="loginPhone = 1" style="cursor:pointer">验证码登录</span>
          </div>
          <el-form :model="loginPassForm" :rules="loginPassRules" ref="loginPass" key="loginP">
            <el-form-item prop="name">
              <el-input
                placeholder="请输入用户名"
                v-model.trim="loginPassForm.name"
                prefix-icon="el-icon-user"
              ></el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input
                type="password"
                placeholder="请输入密码"
                v-model.trim="loginPassForm.pass"
                prefix-icon="el-icon-lock"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <el-row type="flex" align="middle">
                <el-col :span="15">
                  <el-input placeholder="请输入验证码" v-model.trim="loginPassForm.code"></el-input>
                </el-col>
                <el-col :span="8" :push="1">
                  <div class="login-code" @click="refreshCode">
                    <!--验证码组件-->
                    <s-identify :identifyCode="identifyCode"></s-identify>
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <div class="submit-btn" @click="onSubmit('loginPass')">登录</div>
            </el-form-item>
          </el-form>
          <div class="regis-btn" @click="herfTo('register')">去注册>></div>
        </div>
        <!-- 手机短信登录 -->
        <div class="main-card" v-if="loginPhone==1">
          <div class="title flex_ai_c flex_jc_sb">
            <span>欢迎登录</span>
            <span @click="loginPhone = 0" style="cursor:pointer">账号密码登录</span>
          </div>
          <el-form :model="loginMsgeForm" :rules="loginMsgeRules" ref="loginMsge" key="loginM">
            <el-form-item prop="phoneNum">
              <el-input
                placeholder="请输入手机号"
                v-model.trim="loginMsgeForm.phoneNum"
                prefix-icon="el-icon-mobile"
              ></el-input>
            </el-form-item>
            <el-form-item prop="phoneCod">
              <el-row type="flex" align="middle">
                <el-col :span="15">
                  <el-input placeholder="请输入验证码" v-model.trim="loginMsgeForm.phoneCod"></el-input>
                </el-col>
                <el-col
                  :span="8"
                  :push="1"
                  v-if="codeTimeShow"
                  @click.native="sendCode('loginMsge')"
                >
                  <div class="phone-code-btn">获取验证码</div>
                </el-col>
                <el-col :span="8" :push="1" v-if="!codeTimeShow">
                  <div class="phone-code-btn" style="color: #ccc">{{sendCodeTime+'s'}}</div>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item>
              <div class="submit-btn" @click="onSubmit('loginMsge')">登录</div>
            </el-form-item>
          </el-form>
          <div class="regis-btn" @click="herfTo('register')">去注册>></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import md5 from 'js-md5'
import {getSmscode} from '@/api/publicMd'
import {login} from '@/api/user'

import SIdentify from '@/components/common/SIdentify' // 随机验证码
import {validateRules} from '@/utils/validateRules'

export default {
  name: 'login',
  components: {
    SIdentify
  },
  data() {
    var validatePassCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (this.loginPassForm.code !== this.identifyCode) {
        callback(new Error('请输入正确的验证吗'))
      }
      callback()
    }
    var validateMsgeCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入验证码'))
      } else if (this.loginMsgeForm.phoneCod !== this.identifyCode) {
        callback(new Error('请输入正确的验证吗'))
      }
      callback()
    }
    return {
      timer: '',
      redirectPath: null,
      loginPhone: 0,
      // 账号密码登录------------------------------------------------------------------------------
      identifyCodes: '1234567890',
      identifyCode: '',
      loginPassForm: {
        name: '',
        pass: '',
        code: ''
      },
      loginPassRules: {
        name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        pass: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, message: '密码长度最少为6位', trigger: 'blur'}
        ],
        code: [{validator: validatePassCode, trigger: 'blur'}]
      },
      // 手机短信登录------------------------------------------------------------------------------
      loginMsgeForm: {
        phoneNum: '',
        phoneCod: ''
      },
      loginMsgeRules: {
        phoneNum: [{validator: validateRules.phoneNumber, trigger: 'blur'}],
        phoneCod: [{validator: validateMsgeCode, trigger: 'blur'}]
      },
      sendCodeTime: 60,
      codeTimeShow: true
    }
  },
  created() {
    this.refreshCode()
  },
  mounted() {
    this.identifyCode = ''
    this.makeCode(this.identifyCodes, 4)
  },
  methods: {
    herfTo(name) {
      this.$router.push(`/${name}`)
    },
    getCodeTime() {
      this.codeTimeShow = false
      this.timer = setInterval(() => {
        this.sendCodeTime--
        if (this.sendCodeTime === 0) {
          this.codeTimeShow = true
          this.sendCodeTime = 60
          clearInterval(this.timer)
        }
      }, 1000)
    },
    sendCode(formName) {
      const _self = this
      _self.$refs[formName].validateField('phoneNum', phoneError => {
        if (!phoneError) {
          // 获取手机短信
          getSmscode({
            mobile: _self.loginMsgeForm.phoneNum,
            smsmode: 0
          }).then(res => {
            let {success, message} = res.data
            if (success) {
              _self.$message.success(message)
              // 验证码倒计时
              _self.getCodeTime()
            } else {
              _self.$message.error(message)
            }
          })
        }
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          login({
            loginMode: this.loginPhone,

            mobile: this.loginPhone == 1 ? this.loginMsgeForm.phoneNum : this.loginPassForm.name,

            passWord: md5(this.loginPassForm.pass),
            // passWord: this.loginPassForm.pass,
            smscode: this.loginMsgeForm.phoneCod
          }).then(res => {
            let {success, message} = res.data

            if (success) {
              let {token, userInfo} = res.data.result
              this.$store.commit('SET_TOKEN', token)
              this.$store.commit('SET_USER_INFO', userInfo)
              this.$message.success(message)

              this.herfTo('index')
            } else {
              this.$message.error(message)
            }
          })
        } else {
          return false
        }
      })
    },
    //验证码
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identifyCode = ''
      this.makeCode(this.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identifyCode += this.identifyCodes[this.randomNum(0, this.identifyCodes.length)]
      }
    }
  }
}
</script>

<style lang="less" scoped>
.top {
  position: relative;
}
.login-bg {
  width: 100%;
  min-width: 1920px;
  min-height: 720px;
}
.header-nav {
  position: absolute;
  top: 0;
}
.login-card {
  position: absolute;
  top: 150px;
}
.main-card {
  width: 460px;
  background: #ffffff;
  box-shadow: 1px 4px 21px 0px #104683;
  border-radius: 15px;
  margin-top: 60px;

  box-sizing: border-box;
  padding: 40px;

  .title {
    font-size: 16px;
    color: #343434;
    line-height: 16px;
    padding-bottom: 32px;
    span:nth-child(1) {
      font-size: 24px;
      color: #343434;
      line-height: 24px;
    }
  }
}
.submit-btn {
  background: #0078e8;
  border-radius: 5px;

  font-size: 18px;
  color: #ffffff;
  text-align: center;
  cursor: pointer;
}
.regis-btn {
  padding: 6px;
  font-size: 13px;
  line-height: 13px;
  text-align: center;
  color: #1d3f95;
  cursor: pointer;
}
.phone-code-btn {
  text-align: center;
  padding: 8px;
}
/*验证码样式*/
.login-code {
  cursor: pointer;
}
</style>
